import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/modules/user/user'

let request = axios.create({
  baseURL: '/api', // 基础路径
  timeout: 5000 // 超时时间
})

// 设置拦截器
request.interceptors.request.use((config) => {
  let userStore = useUserStore()
  // 返回 可以在config.headers.token 携带token参数
  if (userStore.token) {
    config.headers.token = userStore.token
  }

  return config
})

request.interceptors.response.use(
  (response) => {
    // 返回简化数据
    return response.data
  },
  (error) => {
    const status = error.response.status
    switch (status) {
      case 404:
        ElMessage({
          type: 'error',
          message: '请求路径错误'
        })
        break
      case 501 | 502 | 503 | 504:
        ElMessage({
          type: 'error',
          message: '服务器错误'
        })
        break
    }
  }
)

export default request
